package com.dap.service.impl;

import com.dap.service.FlowControlService;
import com.dap.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.text.NumberFormat;
import java.util.List;

@Service
public class FlowControlServiceImpl implements FlowControlService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public String getFlowControlRate(Long interval, String applicationName,String interfaceName,String groupName) {

        String result = null;
        String resourceName = getResourceName(applicationName,interfaceName,groupName);

        Long now = System.currentTimeMillis();


        //调试代码
        System.out.println();


        Long all = redisTemplate.boundZSetOps("count" + resourceName).count(now - interval, now);

        System.out.println("*****总数是："+all);

        Long success = redisTemplate.boundZSetOps("success" + resourceName).count(now - interval, now);
        System.out.println("*****成功的数是："+all);
//        Long success = redisTemplate.boundZSetOps("success" + resourceName).count(now - interval, now);

        if(all!=null){
            NumberFormat instance = NumberFormat.getInstance();
            //精确到小数点后2位小数
            instance.setMinimumFractionDigits(2);

            String format = instance.format((float) success / (float) all * 100);
            result = format+"%";
        }
        return result;
    }

    @Override
    public String countSuccess(Long interval, String applicationName,String interfaceName,String groupName) {
        String resourceName = getResourceName(applicationName,interfaceName,groupName);
        long now = System.currentTimeMillis();
        Long success = redisTemplate.boundZSetOps("success" + resourceName).count(now - interval, now);
        return success.toString();
    }

    @Override
    public Long concurrence(Long interval, String applicationName,String interfaceName,String groupName) {
        String resourceName = getResourceName(applicationName,interfaceName,groupName);

        long now = System.currentTimeMillis();

        Long all = redisTemplate.boundZSetOps("count" + resourceName).count(now - interval, now);

        return all;
    }

    @Override
    public String rankOnQueue(String applicationName,String interfaceName,String groupName) {
        String resourceName = getResourceName(applicationName,interfaceName,groupName);

        //当前请求在队列中的位置
        String rank = (String) redisTemplate.opsForValue().get("rank" + resourceName);

        return rank;
    }

    private String getResourceName(String applicationName,String interfaceName,String groupName){
        String resourceName = "FOP:Application:"+applicationName+"/Interface:"+interfaceName+"/Group:"+groupName;
        return resourceName;
    }


}
